package com.hebeu.core.util;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.hebeu.core.model.Page;

public class PageList<T> {
	public List<T> list(Page page, String hql) {
		int pageSize = page.getPageSize();
		int pageNow = page.getPageNow();
		List<T> Records = new ArrayList<T>();

		Session s = HibernateSessionFactory.getSession();
		Query q = s.createQuery(hql);
		Transaction ts = s.beginTransaction();
		q.setFirstResult(pageSize * pageNow - pageSize);
		q.setMaxResults(pageSize);
		Records = q.list();
		ts.commit();
		s.close();
		return Records;
	}

	public Page first(Page page) {
		page.setPageNow(1);
		return page;
	}

	public Page last(Page page) {
		page.setPageNow(page.getLastPage());
		return page;
	}

	public Page pageTotal(int pageSize, String hql) {
		Page page = new Page();
		page.setPageSize(pageSize);
		Session s = HibernateSessionFactory.getSession();
		Query q = s.createQuery(hql);
		Transaction ts = s.beginTransaction();
		List<Page> pages = q.list();
		int totalNum = pages.size();
		int lastPage = totalNum / pageSize;
		if (totalNum % pageSize == 0) {
			page.setLastPage(lastPage);
		} else if (totalNum % pageSize != 0) {
			page.setLastPage(lastPage + 1);
		}

		page.setTotalSize(totalNum);
		page.setPageNow(1);
		return page;
	}
}
